<?php

namespace App\Http\Controllers;

use App\userlist;
use Illuminate\Http\Request;

class UserController extends Controller{
    public function login(Request $request){
        $appid = "wx849a600fb0db3dfd";
        $appSecret = "0e89504db7d67d085cacb8e334091bd0";
        $code = $request['code'];
        $retData = @file_get_contents('https://api.weixin.qq.com/sns/jscode2session?appid='.$appid.'&secret='.$appSecret.'&js_code='.$code.'&grant_type=authorization_code');

        $data = json_decode($retData, true);
        return $data['openid'];
    }
    public function loginload(Request $request){
        try{
            $openid = $request['openid'];
            $nickname = $request['nickname'];
            $avatarUrl=$request['avatarUrl'];
            $oldAvatarUrl = userlist::where('openid','=',$openid) -> select('avatarUrl') -> get();
            if(count($oldAvatarUrl) == 0){
                $userlist = userlist::create([
                    'openid' => $openid,
                    'nickname' => $nickname,
                    'avatarUrl' => $avatarUrl,
                    'Maxscore' =>0
                ]);
                return $userlist;
            }else{
                if($oldAvatarUrl[0]['avatarUrl'] != $avatarUrl){
                    $updateAvatarUrl = userlist::where('openid',$openid) ->update(
                        ['avatarUrl' => $avatarUrl]
                    );
                    return response() ->json($updateAvatarUrl);
                }
                return response() ->json($oldAvatarUrl);
            }
        }catch(PDOException $e){
            echo $e->getMessage();
            echo '<br />';
            echo iconv('gbk', 'utf-8', $e->getMessage());
        }
    }
    public function getcharts(){
        $user = userlist::select('*')
            ->limit(5)
            ->orderBy('Maxscore','desc')
            ->get();
        return $user;
    }
    public function getnextuser(){
        $user =userlist::select('Maxscore','avatarUrl')
            ->groupBy('Maxscore')->paginate(3);
        return $user;
    }
    public function getMaxscore(Request $request){
        $openid = $request['openid'];
        $user = userlist::where('openid','=',$openid)
            ->get();
        return $user;
    }
    public function updateScore(Request $request){
        $openid = $request['openid'];
        $score = $request['score'];
        $updateScore = userlist::where('openid',$openid) ->update(
            ['Maxscore' => $score]
        );
        return $updateScore;
    }

}
